<template>
  <div class="dict-main">
    <el-form :inline="true" v-model="searchParams" class="search-form">
      <el-form-item label="名称" class="form-input">
        <el-input
          v-model.trim="searchParams.name"
          clearable
          @clear="getDictDataList"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="onSubmit(1)"
          >查询</el-button
        >
        <el-button size="small" @click="resetLoad">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="table-wrapper" ref="tableWrapRef">
      <div class="table-title" ref="tableTitleRef">
        <span class="table-title-text">字典数据</span>
        <div style="display: inline-flex">
          <el-button
            v-show="selectDict.name"
            type="primary"
            size="small"
            @click="addDataDictionary"
          >
            新增
          </el-button>
          <el-upload
            v-show="selectDict.name"
            ref="uploadRef"
            class="upload-demo"
            :style="{ margin: '0 10px' }"
            action=""
            accept=".xls"
            :limit="1"
            :show-file-list="false"
            :http-request="customUpload"
          >
            <el-button type="primary" size="small"> 导入 </el-button>
          </el-upload>
          <el-button
            v-show="selectDict.name"
            type="primary"
            size="small"
            @click="exportData"
          >
            导出
          </el-button>
        </div>
      </div>
      <el-table
        v-loading="loading"
        :key="refresh"
        :max-height="fixedHeight"
        :data="tableList"
        :cell-style="{ color: '#333333' }"
        :header-cell-style="{ background: '#F3F4F7', color: '#000000' }"
      >
        <el-table-column
          type="index"
          label="序号"
          width="50"
          align="center"
          fixed="left"
        ></el-table-column>
        <el-table-column
          prop="name"
          label="名称"
          width="200"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="编码"
          align="center"
          width="200"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            {{ scope.row.code || "---" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="parentName"
          label="父级"
          width="150"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.parentName || "---" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="sort"
          label="排序"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="enableState"
          label="是否启用"
          width="150"
          align="center"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.enableState"
              :active-value="0"
              :inactive-value="1"
              @change="changeStatus(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="250">
          <template slot-scope="scope">
            <el-link
              :underline="false"
              type="primary"
              class="ontology-edit"
              @click.native.prevent="openEdit(scope.row)"
              >编辑</el-link
            >
            <el-link
              :underline="false"
              type="primary"
              class="ontology-edit"
              @click.native.prevent="deleteRow(scope.row)"
              >删除</el-link
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        ref="paginationRef"
        background
        small
        layout="total, prev, pager, next, sizes, jumper"
        :page-sizes="[10, 20, 30]"
        :total="total"
        :hide-on-single-page="!total"
        :page-size.sync="searchParams.pageSize"
        :pager-count="7"
        :current-page.sync="searchParams.pageNum"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      >
      </el-pagination>
    </div>
    <OperaDialog ref="operaDialogRef" @reload="getDictDataList" />
  </div>
</template>
<script>
import { updateCookie } from "@/plugins/utils/auth";
import OperaDialog from "./tableComponents/OperaDialog.vue";
export default {
  name: "DictDataInfo",
  props: {
    selectType: {
      type: Object,
      default: () => {},
    },
  },
  components: {
    OperaDialog,
  },
  data: () => {
    return {
      fixedHeight: 500,
      refresh: 0,
      searchParams: {
        name: null, // 关键词
        pageNum: 1, // 页码
        pageSize: 10, // 每页条数
      },
      selectDict: {},
      tableList: [], // 数据列表
      total: 0, // 数据总条数
      loading: false,
    };
  },
  watch: {
    selectType: {
      handler(val, oldVal) {
        this.selectDict = val;
        this.getDictDataList();
      },
    },
  },
  created() {
    if (this.$route.query.token) {
      updateCookie("token", this.$route.query.token);
    }
    // 获取数据列表
    this.getDictDataList();
  },
  mounted() {},
  methods: {
    // 获取字典数据
    getDictDataList() {
      this.loading = true;
      this.$axios
        .post(this.$api.dataConnection.dataDictionary.getDictDataByType, {
          ...this.searchParams,
          type: this.selectDict?.name,
        })
        .then((res) => {
          if (res.data.code === 200) {
            let data = res.data.data;
            this.tableList = data.list;
            this.total = data.total;
            this.searchParams.pageSize = data.pageSize;
            this.searchParams.pageNum = data.pageNum;
            this.$nextTick(() => {
              this.calcFixedHeight();
            });
          } else {
            this.$message.error(res.data.message);
          }
        })
        .catch((err) => {
          console.error(err);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    calcFixedHeight() {
      // 高度计算后 修改this.refresh 让vue重新渲染table
      this.fixedHeight =
        this.$refs.tableWrapRef.clientHeight -
        this.$refs.tableTitleRef.clientHeight -
        this.$refs.paginationRef.$el.clientHeight -
        62;
      // 62为边距高度
      this.refresh++;
    },
    // 查询
    onSubmit(pageNum) {
      this.searchParams.pageNum = pageNum ? pageNum : this.searchParams.pageNum;
      this.getDictDataList();
    },
    resetLoad() {
      this.searchParams.pageNum = 1;
      this.searchParams.name = null;
      this.getDictDataList();
    },
    customUpload({ file }) {
      const formData = new FormData();
      formData.append("file", file);
      this.$axios
        .post(this.$api.dataConnection.dataDictionary.importDictData, formData)
        .then((res) => {
          if (res.data.code === 200) {
            this.$message.success(res.data.message || "操作成功");
            this.getDictDataList();
          } else {
            this.$message.warning(res.data.message);
          }
        });
    },
    exportData() {
      this.$axios
        .post(
          this.$api.dataConnection.dataDictionary.exportDictData,
          {
            ...this.searchParams,
            type: this.selectDict?.name,
            code: this.selectDict?.code,
          },
          { responseType: "blob" }
        )
        .then((res) => {
          let fileName;
          if (res.headers["content-disposition"]) {
            const name = res.headers["content-disposition"];
            fileName = window.decodeURI(name.substring(name.indexOf("=") + 1));
          }
          let url = window.URL.createObjectURL(new Blob([res.data]));
          var a = document.createElement("a");
          a.style.display = "none";
          a.href = url;
          a.download = fileName || "字典导出.xls";
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          window.URL.revokeObjectURL(url);
        });
    },
    // 修改当前页码
    handleCurrentChange() {
      this.getDictDataList();
    },
    // 修改每页条数
    handleSizeChange() {
      this.getDictDataList();
    },
    // 新增字典数据
    addDataDictionary() {
      this.$refs.operaDialogRef.openDialog(this.selectDict);
    },
    // 修改状态
    changeStatus(row) {
      this.$confirm(
        `是否确认${row.enableState === 1 ? "禁用" : "启用"}该名称？`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          const params = {
            id: row.dictionaryId,
            enableStatus: Number(row.enableState),
          };
          this.$axios
            .post(this.$api.dataConnection.dataDictionary.ableDictData, params)
            .finally(() => {
              this.getDictDataList();
            });
        })
        .catch(() => {
          row.enableState = row.enableState === 1 ? 0 : 1;
          this.$message.info("已取消");
        });
    },
    openEdit(row) {
      this.$refs.operaDialogRef.openDialog(this.selectDict, row);
    },
    // 删除数据
    deleteRow(row) {
      this.$confirm(`确定删除此数据？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$axios
          .get(this.$api.dataConnection.dataDictionary.deleteDictData, {
            params: {
              id: row.dictionaryId,
            },
          })
          .then((res) => {
            if (res.data.code === 200) {
              this.$message.success(res.data.message || "操作成功");
              this.getDictDataList();
            } else {
              this.$message.warning(res.data.message);
            }
          });
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.dict-main {
  position: relative;

  .search-form {
    padding: 16px 32px;
    border-radius: 4px;
    background: #ffffff;

    .el-form-item {
      margin-bottom: 0;
    }

    .form-input {
      margin-right: 32px;

      /deep/ .el-input__inner {
        width: 240px;
        height: 32px;
        background: #ffffff;
        border-radius: 2px;
        border: 1px solid #e0e0e0;
      }
    }
  }

  .el-select {
    /deep/ .el-input__inner {
      width: 240px;
      height: 32px;
      background: #ffffff;
      border-radius: 2px;
      border: 1px solid #e0e0e0;
    }
  }

  .table-wrapper {
    flex: 1;
    overflow: hidden;
    margin-top: 16px;
    padding: 16px 32px 64px;
    border-radius: 4px;
    background: #ffffff;

    .table-title {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .table-title-text {
        border-left: 5px solid $--color-primary;
        padding-left: 10px;
        margin: 8px 0;
        font-size: 16px;
        line-height: 16px;
      }

      margin-bottom: 10px;
    }

    .little-circle-blue {
      display: inline-block;
      width: 6px;
      height: 6px;
      border-radius: 3px;
      background: #55c898;
      position: relative;
      right: 4px;
      top: -2px;
    }

    .little-circle-red {
      display: inline-block;
      width: 6px;
      height: 6px;
      border-radius: 3px;
      background: #ee5564;
      position: relative;
      right: 6px;
      top: -2px;
    }

    .page-wrapper {
      margin-top: 28px;
      display: flex;
      justify-content: flex-end;
      color: rgba(0, 0, 0, 0.65);

      .data-counter {
        font-weight: 400;
        line-height: 32px;
        margin-right: 24px;
      }

      /deep/ .btn-prev,
      /deep/ .btn-next {
        margin: 0 4px;
        min-width: 28px;
        border-radius: 2px;
        border: 1px solid rgba(0, 0, 0, 0.15);
        padding: 0;
      }

      /deep/ .el-pager .number {
        min-width: 28px;
        height: 28px;
        border-radius: 2px;
        border: 1px solid rgba(0, 0, 0, 0.15);
        margin: 0 4px;
        cursor: pointer;
      }
    }
  }

  .ontology-edit {
    padding: 0 10px;

    & + .ontology-edit {
      border-left: 1px solid #dddddd;
    }
  }

  /deep/ .el-table__append-wrapper {
    padding: 10px;
  }

  .el-pagination {
    float: right;
    margin-top: 20px;

    .form-input /deep/ .el-input {
      width: 200px;
    }

    /deep/ .el-input__inner {
      height: 22px;
    }
  }

  /deep/ .el-dialog {
    border-radius: 5px;
  }
}
</style>
